import React from 'react'
import { Table, Checkbox, Tooltip, Select, message, Modal, } from 'antd'
import './add_product_modal.sass'
import moment from 'moment'
import cookie from 'js-cookie'
import axios from '../../../Utils/axios'
import locale from 'antd/es/locale/zh_CN'
import 'moment/locale/zh-cn'
moment.locale('zh-cn')

const Option = Select.Option;
const confirm = Modal.confirm;
export default class CompanyTable extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      dataSource: [],
      sumCount: '',
      pageSize: 10,
      currentPage: 1,
      rateValue: 'year',
      rateStatus: false,
      columns: [
        {
            title: () => {
                return (<span href='/'>收藏</span>)
            },
            dataIndex: 'attentions',
            key: '1',
            width: 70,
            fixed: 'left',
            render: (t, r) => {
                let id = r.fundId
                if (r.isFav === 0) {
                    return (<span data-id={`${id}`} id={`${id}`} className={`iconfont iconguanzhu heart_check`} onClick={this.headerCheck} />)
                } else {
                    return (<span data-id={`${id}`} id={`${id}`} className={`iconfont iconyiguanzhu heart_check`} onClick={this.headerCheck} />)
                }
            }
        },
        {
            title: '对比',
            dataIndex: 'compare',
            key: '2',
            width: 70,
            fixed: 'left',
            render: (t, r) => {
                const stroageId = window.sessionStorage.getItem("attentionArr") ? JSON.parse(window.sessionStorage.getItem("attentionArr")).fundId : [];
                const status = stroageId.indexOf(`${r['fundId']}`) !== -1 ? true : false
                return (this.props.query&&(this.props.query.id===r['fundId'])?
                <Checkbox defaultChecked disabled id={`${r['fundId']}`} name={r['fundName']} onChange={this.changes}></Checkbox>:
                <Checkbox checked={status} id={`${r['fundId']}`} name={r['fundName']} onChange={this.changes}></Checkbox>)
            }
        },
        {
            title: '序号',
            dataIndex: 'key',
            width: 70,
            fixed: 'left',
            key: '3',
            render: (text) => (<span>{text!== '' ? text : '--'}</span>)
        },
        {
            title: '产品名称',
            sorter: true,
            sortDirections: ['descend', 'ascend'],
            dataIndex: 'fundName',
            key: '4',
            className: 'text_align_left',
            ellipsis: true,
            render: (text, recoder) => (<Tooltip placement="bottom" title={text}>
                {text ?
                <a className='table_color table_href' rel="noopener noreferrer" target="_blank" href={`/product?id=${recoder.fundId}&name=${encodeURI(text)}`}>{text ? text : '--'}</a>
                : <span>{text ? text : '--'}</span>
                }
                </Tooltip>)
        },
        {
            title: '投顾名称',
            sorter: true,
            sortDirections: ['descend', 'ascend'],
            dataIndex: 'fundConsultant',
            key: '5',
            ellipsis: true,
            render: (text, recoder) => {
            let results = ``
            if (text) {
                results = <a  className='table_color table_href' rel="noopener noreferrer" target="_blank" href={`/advisor?id=${recoder.orgId}`}>{text ? text : '--'}</a>
            } else {
                results = <span className='table_color table_href'>{text ? text : '--'}</span>
            }
            return results
            }
        },
        {
            title: '投资经理',
            sorter: true,
            sortDirections: ['descend', 'ascend'],
            dataIndex: 'fundManager',
            key: '6',
            ellipsis: true,
            render: (text, recoder) => {
                let results = ``
                if (text) {
                    results = <a className='table_color table_href' rel="noopener noreferrer" target="_blank" href={`/manager?id=${recoder.fundManagerId}`}>{text ? text : '--'}</a>
                } else {
                    results = <span className='table_color table_href'>{text ? text : '--'}</span>
                }
                return results
            }
        },
        {
          title:  '复权累计净值',
          sorter: true,
          sortDirections: ['descend', 'ascend'],
          key: '12',
          className: 'fund_nav_filters',
          dataIndex: 'fundNav',
          render: (text) => {
              let content = text === undefined ? '--' : text
          return (<span>{`${isNaN(parseFloat(content)) ? '--' : parseFloat(content).toFixed(4)}`}</span>)
          }
        },
        {
            title: () => (
            <div className='home_table_rate'>
                <span>收益率</span>
                <Select
                id='rateSelection'
                style={{marginLeft: 10, width: 120}}
                value={this.props.date_type}
                open={this.state.rateStatus}
                onChange={this.changeRate}>
                <Option className={'rate_select_options'} value="year" data-key="year">今年以来</Option>
                <Option className={'rate_select_options'} value="m1" data-key="m1">近一月</Option>
                <Option className={'rate_select_options'} value="m3" data-key="m3">近三月</Option>
                <Option className={'rate_select_options'} value="m6" data-key="m6">近六月</Option>
                <Option className={'rate_select_options'} value="y1" data-key="y1">近一年</Option>
                <Option className={'rate_select_options'} value="y2" data-key="y2">近二年</Option>
                <Option className={'rate_select_options'} value="y3" data-key="y3">近三年</Option>
                <Option className={'rate_select_options'} value="total" data-key="total">成立以来年化</Option>
                </Select>
            </div>
          ),
            sorter: true,
            key: '13',
            dataIndex: 'nReturn',
            sortDirections: ['descend', 'ascend'],
            onClick: (event) => {console.log(event)},
            render: (text) => {
                let content = text === undefined ? '--' : text
                return (<span className={content > 0 ? 'color_number_red' : 'color_number_green'}>{`${isNaN(parseFloat(content)) ? '--' : parseFloat(content).toFixed(2)+'%'}`}</span>)
            }
        }]
    }
  }

  componentDidMount() {
      const rateEle = document.getElementById('rateSelection')
      rateEle.addEventListener('click', (e) => {
          e.stopPropagation()
          this.setState({rateStatus: !this.state.rateStatus})
          const list = document.querySelectorAll('.rate_select_options')
          Array.from(list).forEach(item => {
              item.addEventListener('click', this.stopRate, false)
          })
      }, false)
  }

    changeRate = (e) => {
        this.props.changeRate(e)
    }  

     headerCheck = (e) => {
        let _this = this
        let status = e.target.getAttribute('class')
        let id = e.target.getAttribute('data-id')
        const element = e.target
        if (status.indexOf('iconguanzhu') !== -1) {
            const target = e.target
            this.addGroup(id, target)
        } else {
            confirm({
                title: '取消收藏',
                content: '您确定要取消收藏本产品吗？',
                okText: '确定',
                centered: true,
                cancelText: '取消',
                onOk: () => {
                    axios({
                        method: 'POST',
                        url: '/hsApi/hszcpz/attention/delAttention',
                        data: JSON.stringify({
                            // "token": cookie.get('token'),
					        "token": "88d34ede-9302-4b5a-8701-4e940d425d9b",
                            "fgroup_id":"1003",
                            "fav_object_id": id
                        })}
                    )
                        .then(data => {
                            document.getElementById(id).setAttribute('class', 'iconfont iconguanzhu heart_check')
                            if (data.status !== 'success') {
                                message.info(data.errorReason)
                                return
                            }
                            data = JSON.parse(data)
                            if (data.result === 'success') {
                                element.setAttribute('class', 'iconfont iconguanzhu heart_check')
                                _this.setState({visible: false})
                            } else {
                                message.destroy()
                                message.error(data.reason)
                            }
                        })
                },
                onCancel () {}
            })
        }

    } 
    
    addGroup = (e, target) => {
        axios({
            method: 'POST',
            url: '/hsApi/hszcpz/attention/addAttention',
            data: JSON.stringify({
                // "token": cookie.get('token'),
                "token": "88d34ede-9302-4b5a-8701-4e940d425d9b",
                "fgroup_id":"1003",
                "fav_object_id": e
            })}
        )
        .then(data => {
            message.destroy()
            if (data.status !== 'success') {
                message.info(data.errorReason)
                return
            }
            data = JSON.parse(data.result)
            if (data.result === 'success') {
                target.setAttribute('class', 'iconfont heart_check iconyiguanzhu')
                this.setState({visible: false})
                message.success(data.reason)
            } else {
                message.error(data.reason)
            }
        })

    }    

  stopRate = (e) => {
    const value = e.target.dataset.key;
    this.setState({
      rateValue: value,
      rateStatus: false
    })
  }

changes = (e) => {
        const attentionArr = window.sessionStorage.getItem("attentionArr") ? JSON.parse(window.sessionStorage.getItem("attentionArr")) : { fundName: [], fundId: [] }
        if (e.target.checked) {
            if (attentionArr.fundId.length > 5) {
                Modal.info({
                    content: '最多选择6个产品与本产品比较',
                });
            } else {
                attentionArr.fundId = attentionArr.fundId.concat(e.target.id.split())
                attentionArr.fundName = attentionArr.fundName.concat(e.target.name.split())
            }
      } else {
          attentionArr.fundId = attentionArr.fundId.filter((item) => item !== e.target.id)
          attentionArr.fundName = attentionArr.fundName.filter((item) => item !== e.target.name)
      }
        window.sessionStorage.setItem("attentionArr", JSON.stringify(attentionArr))
        window.sessionStorage.setItem("stroageId", attentionArr.fundId)
}

tableChange = (pagination, filter, sorter, e) => { 
    this.props.tableChange(pagination)
}
	
changeSize = (page, size) => {
	this.props.changeSize(page, size)
}
render() {
    const { columns,  } = this.state;
    const { dataSource, pageSize, sumCount, currentPage, takeDate } = this.props;
    return(
      <div>
        <Table 
            className={`companyTable`}
            style={{marginTop: '30px'}}
            locale={locale}
            dataSource={dataSource}
            columns={columns}
            loading={this.props.loading}
            onChange={this.tableChange.bind(this)}
            pagination={{ showSizeChanger: true,
              showQuickJumper: true,
              current: currentPage,
              pageSizeOptions: ['5', '10', '20', '50', '100'],
              pageSize: pageSize,
              onShowSizeChange: this.changeSize,
              total: this.props.sumCount,
              className: 'add_modal_pagination',
              showTotal: (total) => <span className={'table_data_total'}>共<i className={'color_red total_data_size'}>{dataSource.length > 0 ? sumCount || total: '0'}</i>条数据 <span>更新日期： <i>{moment(takeDate).format('YYYY-MM-DD')}</i></span></span> }} />
      </div>
    )
  }
};
